package com.game.logic.roles;

import akka.actor.ActorRef;
import com.coment.cfg.luban.Tables;
import com.coment.cfg.luban.constant.AIDCFG;
import com.coment.game.fight.Attribute;
import com.coment.game.fight.Attrs;
import com.coment.message.EquipmentInformationMessage;
import com.coment.message.roles.UpgradeSkill;
import com.coment.po.roles.Roles;
import com.coment.vo.RolesInfo;
import com.coment.vo.RolesListItem;
import com.game.dao.user.UserPlayInfoDao;
import com.game.dao.user.roles.RolesDao;
import com.game.logic.core.comment.Bonus;
import com.game.logic.fighting.actor.RolesActor;
import com.game.logic.fighting.attrs.AttrsManagement;
import com.game.logic.items.bonus.BonusService;
import com.xs.build.server.websocket.channel.ClientManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@AllArgsConstructor
@Slf4j
@Service
public class RolesService {
    public static final Map<String, Integer> nameAndCardId;
    public final RolesDao rolesDao;
    private final UserPlayInfoDao userPlayInfoDao;
    private final AttrsManagement attrsManagement;

    static {
        nameAndCardId = Tables.cfg.get_tbcardtalentconfig().getDataList()
                .stream()
                .collect(Collectors.toMap((k) -> k.CardName, (v) -> v.ID));
    }

    /// 获取免费角色
    public void tryObtainFreeRole(Integer userInfoId, Integer anchorInfoId) {
        if (!this.rolesDao.existsByUserInfoId(userInfoId)) {
            Bonus<Integer> integerBonus = BonusService.bonusPoll.get(1);
            List<Integer> bonusValue = integerBonus.getBonusValue();
            bonusValue.forEach(cardId -> ClientManager.sendMessageToClient(anchorInfoId,
                    this.tryObtainRoles(userInfoId, cardId))
            );
            log.debug("获取角色：{}", bonusValue);
        }
    }

    /// 获取或升星
    public Roles tryObtainRoles(Integer userInfoId, Integer cardId) {
        if (!this.rolesDao.existsByUserInfoIdAndCardId(userInfoId, cardId)) {
            return obtainRoles(userInfoId, cardId);
        } else {
            return tryRisingStar(this.rolesDao.searchByUserInfoIdAndCardId(userInfoId, cardId));
        }
    }

    /// 获取角色
    private Roles obtainRoles(Integer userInfoId, Integer cardId) {
        Roles roles = new Roles(userInfoId, cardId);
        return this.rolesDao.insert(roles);
    }

    /// 尝试升星
    private Roles tryRisingStar(Roles roles) {
        Integer userInfoId = roles.getUserInfoId();
        Integer lastAnchorInfoId = userPlayInfoDao.findByUserInfoIdOrCreate(userInfoId).getRecentlyPlayedAnchorInfoId();

        Attrs attrs = RolesCultivateLogic.tryRisingStar(roles);
        Attrs attrsGlobal = attrsManagement.logAttrsGlobal(userInfoId, attrs, "card:", roles.getCardId(), "star");

        log.debug("全局属性为：{}", Attribute.getLogInfo(attrsGlobal));
        ClientManager.sendMessageToClient(lastAnchorInfoId, roles);
        return this.rolesDao.save(roles);
    }

    /// 渡劫
    public Roles tryCrossingTheTribulation(@NotNull String rolesId) {
        Roles roles = this.rolesDao.findByIdMust(rolesId);
        Integer userInfoId = roles.getUserInfoId();
        Integer lastAnchorInfoId = userPlayInfoDao.findByUserInfoIdOrCreate(userInfoId).getRecentlyPlayedAnchorInfoId();

        Attrs attrs = RolesCultivateLogic.tryBreakthrough(roles);
        Attrs attrsGlobal = attrsManagement.logAttrsGlobal(
                userInfoId,
                attrs,
                "card:", roles.getCardId(), "xtqy"
        );

        log.debug("渡劫后全局属性为：{}", Attribute.getLogInfo(attrsGlobal));
        ClientManager.sendMessageToClient(lastAnchorInfoId, roles);
        this.rolesDao.save(roles);
        return roles;
    }

    /// 查询装备
    public EquipmentInformationMessage selectEquip(String seatRolesId) {
        Roles roles = this.rolesDao.findByIdMust(seatRolesId);
        Map<Integer, Set<Integer>> inventory = roles.rolePanel.cultivatePanel.inventory;
        return new EquipmentInformationMessage(seatRolesId, inventory);
    }

    /// 获取战斗力
    public Double obtainRoleFightPower(@NotNull String rolesId) {
        Roles roles = this.rolesDao.findByIdMust(rolesId);
        return RolesCultivateLogic.tryCountFightingCapacity(roles);
    }

    /// 获取体力
    public Integer obtainRoleStrength(@NotNull String rolesId) {
        return null;
    }


    /// 升级技能
    public Roles tryUpgradeSkill(String rolesId) {
        UpgradeSkill message = new UpgradeSkill(rolesId);
        RolesActor.getRolesActor(rolesId).tell(message, ActorRef.noSender());
        return rolesDao.findByIdMust(rolesId);
    }

    //  ------------------------------------------------  select 查询
    public List<RolesListItem> getRolesListItems(Integer[] userInfoIds) {
        List<RolesListItem> rolesListItems = new ArrayList<>();
        for (Integer userInfoId : userInfoIds) {
            RolesListItem rolesListItem = new RolesListItem(
                    new Attrs(),
                    userInfoId,
                    new ArrayList<>()
            );
            for (Roles roles : rolesDao.searchAllByUserInfoId(userInfoId)) {
                RolesInfo rolesInfo = new RolesInfo(
                        roles.id,
                        roles.cardId,
                        roles.rolePanel.getCultivatePanel().getBase().get(AIDCFG.level).intValue(),
                        roles.rolePanel.getCultivatePanel().getBase().get(AIDCFG.star).intValue(),
                        roles.skillLv,
                        RolesCultivateLogic.tryCountFightingCapacity(roles)
                );
                rolesListItem.addRolesInfo(rolesInfo);
            }
            rolesListItems.add(rolesListItem);
        }
        return rolesListItems;
    }
}
